<template>
  <div class="rightBodyContent">
    <div class="rightBodyContent-in">
      <div class="hearder-search">
        <div class="toplineBox mb-10">
          <div class="toplineBox-left">
            <el-button type="primary" size="small" icon="el-icon-date" @click="HistoryList(0)">自主历史</el-button>
            <el-button type="primary" size="small" icon="el-icon-date" @click="HistoryList(1)">被授历史</el-button>
            <el-button size="small" icon="el-icon-date" @click="HistoryList(2)">授出历史</el-button>
          </div>
        </div>
      </div>
      <div class="breadcrumb-container input-val-box">
        <div class="search_box">
          <el-select placeholder="学年" v-model="searchFrom.year" size="small"
                     class="w-140 mr-10">
            <el-option :label="item.year" :value="item.id" v-for="(item, index) in yearList"
                       :key="index"></el-option>
          </el-select>
          <el-select placeholder="周" v-model="searchFrom.week" size="small"
                     class="w-140 mr-10">
            <el-option :label="item.name" :value="item.id" v-for="(item, index) in weekList"
                       :key="index"></el-option>
          </el-select>
        </div>
        <el-button type="primary" @click="searchBtn" size="small"><i class="el-icon-search"></i>查询</el-button>
        <el-button size="small" @click="refreshFn"><i class="el-icon-refresh"></i>刷新</el-button>
      </div>
      <div class="tips-schedule mb-20">
        <p>
          <span></span>
          自主日程;
        </p>
        <p>
          <span></span>
          被授日程;
        </p>
        <p class="top-line">
          <i class="iconfont iconjinggao"></i>
          待确认日程;
        </p>
        <p class="back-line-none">
          <span></span>
          驳回日程;
        </p>
        <p>右击时间段添加自主日程；</p>
      </div>
      <div class="table-body-task">
        <h2><small>{{ Weekdate }} {{ weekName }} {{ Weektime }}</small>日程安排 </h2>
        <!--        本周-->
        <div v-for="(item ,index) in myOptionData">
          <div class="table-body-title">
            <div class="table-body-title-line">
              {{ item[0].year }}/{{ item[0].teach_week }}周
              <!--              ({{ index == 0 ? '本周' : '下周' }})-->
            </div>
            <div class="table-body-title-line-time">
              <div class="table-body-title-line-time-line" v-for="time in timeList">
                {{ time.start_time }} - {{ time.end_time }}
              </div>
            </div>
          </div>
          <div class="table-body-title-list">
            <div class="table-list" v-for="(weekDay,dayIndex) in item" :class="!weekDay.daystatus?'notEditLine':''">
              <div class="table-list-box-time">
                {{ weekDay.day }}
              </div>
              <div class="table-list-box-week">
                {{ week[weekDay.week] }}
                <span class="today-box" v-if="weekDay.day==Weekdate">今</span>
              </div>
              <div class="table-list-box-task" :class="[times.id==mouseHover?'hoverBox':'',!times.dayTimeStatus?'notEditLine':'']"
                   v-for="(times,timeIndex) in weekDay.schedule" @mouseover="changeActive($event,times)"
                   @mouseout="removeActive" @contextmenu.prevent="openMenu($event,index,dayIndex,timeIndex)">
                <!--                                事件提醒模块-->
                <el-popover
                    placement="top"
                    width="200"
                    trigger="hover"
                    v-model="timeTask.visible"
                    v-for="(timeTask,timeTaskIndex) in weekDay.schedule[timeIndex].list">
                  <!--                  timeTask.type==1 别人授权来的 0 我的-->
                  <div v-if="timeTask.type" class="taskProBox">
                    <p><span>授出人:</span>{{ timeTask.inviter.realname }}</p>
                    <p><span>详情:</span>{{ timeTask.title }}</p>
                    <p v-if="timeTask.remind"><span>提醒:</span>{{ timeTask.remind }}</p>
                    <!--                    0 待审核 1 通过 2 驳回 -->
                    <p class="taskProBox-stauts">
                      <span>状态:</span>
                      <span>{{ timeTask.status == 0 ? '未处理' : timeTask.status == 1 ? '已接受' : '已驳回' }}</span>
                      <em v-if="timeTask.status==0&& !weekDay.daystatus">（已过期）</em>
                    </p>
                  </div>
                  <div v-else class="taskProBox">
                    <p><span>详情:</span>{{ timeTask.title }}</p>
                    <p v-if="timeTask.remind"><span>提醒:</span>{{ timeTask.remind }}</p>
                  </div>

                  <div v-if="weekDay.daystatus">
                    <div style="text-align: right; margin: 0" v-if="timeTask.type">
                      <el-button size="mini" type="text"
                                 @click="userGetSchedule(1,index,dayIndex,timeIndex,timeTaskIndex)"
                                 v-if="timeTask.status==0">
                        取消日程
                      </el-button>
                      <el-button type="primary" size="mini"
                                 @click="userGetSchedule(2,index,dayIndex,timeIndex,timeTaskIndex)"
                                 v-if="timeTask.status==0">
                        接受日程
                      </el-button>
                    </div>
                    <div style="text-align: right; margin: 0" v-else>
                      <el-button type="danger" size="mini" @click="handleDetel(timeTask)">删除</el-button>
                    </div>
                  </div>

                  <div slot="reference" class="table-list-box-task-detail my-task" v-if="timeTask.type==0">
                    <p class="detail-title-box">{{ timeTask.title }}</p>
                  </div>
                  <div slot="reference" v-if="timeTask.type==1">
                    <!--                    0 待审核 1 通过 2 驳回 -->
                    <div class="table-list-box-task-detail dufultTitle" v-if="timeTask.status==0">
                      <p class="detail-title-box"><i class="iconfont iconjinggao"></i>{{ timeTask.title }}</p>
                    </div>
                    <div class="table-list-box-task-detail order-task" v-if="timeTask.status==1">
                      <p class="detail-title-box">{{ timeTask.title }}</p>
                    </div>
                    <div class="table-list-box-task-detail dufultTitle detelTitle" v-if="timeTask.status==2">
                      <p class="detail-title-box">{{ timeTask.title }}</p>
                    </div>
                  </div>
                </el-popover>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <ul class='contextmenu' v-show="visibleFn" :style="{left:left+'px',top:top+'px'}">
      <li @click="addMySchedule">新增我的日程</li>
    </ul>
    <timeTaskHistory :visible.sync="historyBox.visible" :optionData="historyBox"></timeTaskHistory>
    <addDayTime :visible.sync="MySchedule.visible" :optionData="MySchedule.optionData" @checkInit="InitFn"></addDayTime>
  </div>
</template>

<script>
import timeTaskHistory from '@/components/dialog/timeTaskHistory'
import addDayTime from '@/components/dialog/addDayTime'
import {weekList} from '@/utils/util.js'

export default {
  components: {
    timeTaskHistory,
    addDayTime
  },
  data () {
    return {
      timeList: [], // 时间段列表
      Weekdate: '--',
      Weektime: '--',
      weekName: '--',
      week: ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
      visibleFn: false, // 右键
      top: 0,
      left: 0,
      historyBox: {
        visible: false, // 弹窗状态
        type: '' // 类型 1 我的 2 被授权
      },
      myOptionData: [],
      mouseHover: '',
      MySchedule: {
        visible: false, // 弹窗状态
        optionData: ''
      },
      searchFrom: {
        year: '',
        week: ''
      },
      yearList: [],
      weekList: weekList
    }
  },
  watch: {
    visibleFn (value) {
      if (value) {
        document.body.addEventListener('click', this.closeMenu)
      } else {
        document.body.removeEventListener('click', this.closeMenu)
      }
    }
  },
  created () {
    this.timerID = setInterval(() => {
      this.updateTime()
    }, 1000)
    // 获取页面数据
    this.dayListFn()
    this.InitFn()
  },
  methods: {
    InitFn () {
      this.$fetch(this.api.schedule.scheduleMy, {}).then((response) => {
        let dayList = []
        let week = []
        for (let i in response.list) {
          let cd = new Date()
          let oDate1 = new Date(this.zeroPadding(cd.getFullYear(), 4) + '-' + this.zeroPadding(cd.getMonth() + 1, 2) + '-' + this.zeroPadding(cd.getDate(), 2))
          let oDate2 = new Date(response.list[i].day)
          if (oDate1.getTime() > oDate2.getTime()) {
            response.list[i].daystatus = false // 日程可否编辑
            // 判断的是天 还需要判断小时 schedule
          } else {
            response.list[i].daystatus = true
          }

          for (let n in response.list[i].schedule) {
            if (response.list[i].schedule[n].list.length) {
              for (let m in response.list[i].schedule[n].list) {
                response.list[i].schedule[n].list[m].visible = false
              }
            }
            // 判断的是天 还需要判断小时 schedule是否可以操作
            let timeOption_ = response.list[i].day
            let startime = timeOption_.replace('/-/g', '/') + ' ' + response.list[i].schedule[n].start_time// 时间转换
            let endtime = timeOption_.replace('/-/g', '/') + ' ' + response.list[i].schedule[n].end_time// 时间转换
            // //时间
            let date1 = new Date(startime)
            let date3 = new Date(endtime)
            // //现在时间
            let date2 = new Date()
            // //判断时间是否过期
            if (oDate1.getTime() <= oDate2.getTime()) {
              // 判断他的时间段是否比开始时间大比结束时间小
              if (date1 < date2) {
                // 开始时间小于现在
                response.list[i].schedule[n].dayTimeStatus = false
              } else {
                response.list[i].schedule[n].dayTimeStatus = true
              }
            }
          }
          if (Number(i) === 0) {
            this.timeList = response.list[i].schedule
            for (let typeNum in response.list[i].schedule[0].list) {
              if (Number(typeNum) === 0) {
                // type 0 我的 1 别人的 2 代办 3 确认 4 取消
                let list_ = JSON.parse(JSON.stringify(response.list[i].schedule[0].list[0]))
                list_.type = 2
                list_.title = '还未处理的日程安排'
                response.list[i].schedule[0].list.push(list_)

                let list_1 = JSON.parse(JSON.stringify(response.list[i].schedule[0].list[0]))
                list_1.type = 3
                list_1.title = '已经确认的日程安排'
                response.list[i].schedule[0].list.push(list_1)

                let list_2 = JSON.parse(JSON.stringify(response.list[i].schedule[0].list[0]))
                list_2.type = 4
                list_2.title = '已经驳回的日程安排'
                response.list[i].schedule[0].list.push(list_2)
              }
            }
            console.log('response.list[i].schedule[0].list:', response.list[i].schedule[0].list)
          }
          dayList.push(response.list[i])
          if (Number(response.list[i].week) === 0) {
            week.push(dayList)
            dayList = []
          }
        }
        this.myOptionData = week
        console.log('week', week)
      }).catch((err) => {
        console.log(err)
      })
    },
    dayListFn () {
      this.$fetch(this.api.setting.semesterIndex, {}).then((response) => {
        for (let i in response.list) {
          if (response.list[i].type === 1) {
            response.list[i].year = response.list[i].year + ' 下学期'
          } else {
            response.list[i].year = response.list[i].year + ' 上学期'
          }
        }
        this.yearList = response.list
      }).catch((err) => {
        console.log(err)
      })
    },
    updateTime () {
      let cd = new Date()
      this.Weektime = this.zeroPadding(cd.getHours(), 2) + ':' + this.zeroPadding(cd.getMinutes(), 2) + ':' + this.zeroPadding(cd.getSeconds(), 2)
      this.Weekdate = this.zeroPadding(cd.getFullYear(), 4) + '-' + this.zeroPadding(cd.getMonth() + 1, 2) + '-' + this.zeroPadding(cd.getDate(), 2)
      this.weekName = this.week[cd.getDay()]
    },
    zeroPadding (num, digit) {
      let zero = ''
      for (let i = 0; i < digit; i++) {
        zero += '0'
      }
      return (zero + num).slice(-digit)
    },
    addMySchedule () {
      this.MySchedule.visible = true
      // optionData
    },
    // 右键关闭
    openMenu (e, weekindex, dayIndex, timeIndex) {
      // dayTimeStatus
      // schedule
      if (this.myOptionData[weekindex][dayIndex].schedule[timeIndex].dayTimeStatus) {
        this.left = e.clientX
        this.top = e.clientY

        let dataOption = {
          day: this.myOptionData[weekindex][dayIndex].day,
          time: this.myOptionData[weekindex][dayIndex].schedule[timeIndex]
        }
        this.MySchedule.optionData = JSON.stringify(dataOption)
        this.visibleFn = true
      } else {
        this.$message.error('时间已过不可添加')
      }
    },
    closeMenu () {
      this.MySchedule.optionData = ''
      this.visibleFn = false
    },
    HistoryList (option) {
      this.historyBox.type = option
      this.historyBox.visible = true
    },
    changeActive (even, time) {
      this.mouseHover = time.id
    },
    removeActive () {
      this.mouseHover = ''
    },
    handleDetel (option) {
      this.$confirm('确认删除本次日程, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.detelRespon(option)
      }).catch(() => {
      })
    },
    detelRespon (option) {
      this.$post(this.api.schedule.scheduleDelete, {id: option.id}).then((response) => {
        if (response.code === 0) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.InitFn()
        } else {
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    searchBtn () {
      // 搜索日程
      this.$fetch(this.api.schedule.scheduleSearchs, this.searchFrom).then((response) => {
        let dayList = []
        let week = []
        for (let i in response.list) {
          let cd = new Date()
          let oDate1 = new Date(this.zeroPadding(cd.getFullYear(), 4) + '-' + this.zeroPadding(cd.getMonth() + 1, 2) + '-' + this.zeroPadding(cd.getDate(), 2))
          let oDate2 = new Date(response.list[i].day)
          if (oDate1.getTime() > oDate2.getTime()) {
            response.list[i].daystatus = false // 日程可否编辑
          } else {
            response.list[i].daystatus = true
          }

          for (let n in response.list[i].schedule) {
            if (response.list[i].schedule[n].list.length) {
              for (let m in response.list[i].schedule[n].list) {
                response.list[i].schedule[n].list[m].visible = false
              }
            }
          }
          if (Number(i) === 0) {
            this.timeList = response.list[i].schedule
          }
          dayList.push(response.list[i])
          if (Number(response.list[i].week) === 0) {
            week.push(dayList)
            dayList = []
          }
        }
        this.myOptionData = week
      }).catch((err) => {
        console.log(err)
      })
    },
    refreshFn () {
      this.searchFrom.year = ''
      this.searchFrom.week = ''
      this.InitFn()
    },
    // 用户接受反驳日程安排
    userGetSchedule (type, index, dayIndex, timeIndex, timeTaskIndex) {
      // type 1 取消 2 接受
      // index 第几周, dayIndex 哪一天, timeIndex 哪个时间段, timeTaskIndex 哪个日程
      let title_ = '确认接受 ' + this.myOptionData[index][dayIndex].schedule[timeIndex].list[timeTaskIndex].inviter.realname + ',' + this.myOptionData[index][dayIndex].day + ',' + this.myOptionData[index][dayIndex].schedule[timeIndex].start_time + '-' + this.myOptionData[index][dayIndex].schedule[timeIndex].end_time + '的日程安排'
      if (type === 1) {
        title_ = '确认取消 ' + this.myOptionData[index][dayIndex].schedule[timeIndex].list[timeTaskIndex].inviter.realname + ',' + this.myOptionData[index][dayIndex].day + ',' + this.myOptionData[index][dayIndex].schedule[timeIndex].start_time + '-' + this.myOptionData[index][dayIndex].schedule[timeIndex].end_time + '的日程安排'
      }
      this.$confirm(title_, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.userGetScheduleFn(type, this.myOptionData[index][dayIndex].schedule[timeIndex].list[timeTaskIndex].id)
      }).catch(() => {
      })
    },
    userGetScheduleFn (type, id) {
      // scheduleadopt: 'schedule/adopt', // adopt 接受
      //     schedulereject: 'schedule/reject', // reject 驳回
      // type 1 取消 2 接受
      let url_ = this.api.schedule.scheduleadopt
      if (type === 1) {
        url_ = this.api.schedule.schedulereject
      }
      this.$post(url_, {id: id}).then((response) => {
        if (response.code === 0) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.InitFn()
        } else {
        }
      }).catch((err) => {
        console.log(err)
      })
    }
  },
  mounted () {
  }
}
</script>
